//
//  Timeline_mvc_tableViewController.m
//  MVC|MVP|MVVM
//
//  Created by Guo Rui on 2017/11/13.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "Timeline_mvc_tableViewController.h"
#import "MVC_TableViewCell.h"
#import "Service.h"
#import "TimelineModel.h"
#import "NSObject+Orientation.h"

@interface Timeline_mvc_tableViewController ()
@property (strong, nonatomic) NSArray <TimelineModel *> *timelineArray;
@end

@implementation Timeline_mvc_tableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MVC_TableViewCell" bundle:nil] forCellReuseIdentifier:@"ID"];
    [self loadServiceData];
}

- (void)loadServiceData
{
    __weak typeof(self) _self = self;
    [[Service sharedInstance] fetchTimelineWithCompletion:^(NSArray *array) {
        _self.timelineArray = array;
        [_self.tableView reloadData];
    }];
}

#pragma mark - Getter

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.timelineArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MVC_TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID" forIndexPath:indexPath];
    
    TimelineModel *model = self.timelineArray[indexPath.row];
    [cell loadData:model];
    
    __weak typeof(cell) _cell = cell;
    cell.likeDidClick = ^{
        model.like = !model.like;
        if (model.like) {
            model.likeCount += 1;
        }
        else {
            model.likeCount -= 1;
        }
        
        [_cell update];
    };
    
    return cell;
}

@end
